<template>
    <div class="dialog-box">
        <el-dialog class="dialog" v-model="visible" :title="title" top="80px" draggable overflow
            :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
            <el-divider />
            <el-form class="form" ref="formRef" :model="form.re" label-width="auto" size="large" style="margin-top: 20px;"
                :rules="rules">
                <el-form-item label="会员类型：">
                    <div class="button-box">
                        <!-- <el-button class="button" :class="{ 'active': isActive === 1 }"
                            @click="handleType(1)">品牌会员卡</el-button>
                        <el-button class="button" :class="{ 'active': isActive === 2 }" @click="handleType(2)"
                            style="margin-left: 22px;">门店会员卡</el-button> -->
                        <el-checkbox-group v-model="form.re.cardType" size="large" border>
                            <el-checkbox-button :value="'1'"
                                disabled>品牌会员卡</el-checkbox-button>
                                <!-- <el-checkbox-button :value="'1'" v-if="isUseBrandCard"
                                :disabled="cardType_disabled.includes('1')">品牌会员卡</el-checkbox-button> -->
                            <el-checkbox-button :value="'2'"
                                :disabled="cardType_disabled.includes('2')">门店会员卡</el-checkbox-button>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                <el-form-item label="会员姓名：" style="margin-bottom: 25px;">
                    <el-input v-model="form.re.name" placeholder="输入姓名" clearable />
                </el-form-item>
                <el-form-item label="手机号码：" prop="mobiles" style="margin-bottom: 25px;">
                    <el-input v-model="form.re.mobiles" placeholder="输入手机号码" clearable />
                </el-form-item>
                <el-form-item label="会员性别：" style="margin-bottom: 25px;">
                    <el-radio-group v-model="form.re.sex">
                        <el-radio value="011001" size="large">男</el-radio>
                        <el-radio value="011002" size="large">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="会员生日：">
                    <el-date-picker v-model="form.re.birthday" type="date" placeholder="选择日期" clear-icon
                        value-format="YYYY-MM-DD" style="width: 100%;" clearable />
                </el-form-item>
            </el-form>
            <div class="label">
                <div class="label-title">会员标签：</div>
                <div class="label-main">
                    <div class="label-value" v-for="(v,k) in selectLabes" :key="v">{{ v.tagName}}</div>
                </div>
                <div class="label-choose" @click="openChooseLab">
                    <img class="addimg" src="https://oss.jtmckj.com/pc/images/vip/addicon.png" alt="">
                    <div class="addbq">添加标签</div>
                </div>
            </div>
            <div class="footer-box">
                <el-button class="cancel" @click="handleCancel">取消</el-button>
                <el-button class="submit" :loading="loading_dialog" @click="handleSubmit">确认</el-button>
            </div>
            <!-- <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel">Cancel</el-button>
                <el-button type="primary" @click="visible = false">
                    Confirm
                </el-button>
            </div>
        </template> -->
        </el-dialog>
    </div>
    <!-- 房台操作弹窗 -->
  <el-dialog top="140px" v-model="showLabel" :close-on-click-modal="false" :show-close="false" class="dailog" width="30%">
    <div class="popup">
        <div class="popup-title">添加标签</div>
        <div class="popup-value">为会员添加标签<text class="popup-value-tip">（可多选）</text>
           </div>
        <div class="popup-main" >
            <!-- <div class="popup-main-title">{{ item.groupName }}</div> -->
            <div class="popup-main-value">
                <div class="popup-main-item" @click="selectLabel(index)" v-for="(item,index) in labelList" :key="index" :class="item.active?'active':''" >{{ item.tagName }}</div>
                
            </div>
            
        </div>
        <div class="popup-btn">
            <div class="popup-btn-cancle" @click="showLabel = false">取消</div>
            <div class="popup-btn-confirm" @click="confirmLabel">确认</div>
        </div>
    </div>
  </el-dialog>
</template>
  
<script setup>
import { validateMobile } from '@/lib/util.js'
import Api from '@/api'
import useConfigStore from '@/store/config'
const configStore = useConfigStore()
const { isUseBrandCard } = configStore.shopInfo
// const  isUseBrandCard  = false
console.log('isUseBrandCard :>> ', isUseBrandCard);
const props = defineProps({
    visible: {
        type: Boolean,
        required: false,
    },
})
const visible = toRef(props, 'visible')
const validator_Mobile = (rule, value, callback) => {
    if (validateMobile(value)) {
        callback()
    } else {
        callback(new Error('The password can not be less than 6 digits'))
    }
}
const rules = reactive({
    mobiles: [
        { required: true, message: '请输入手机号', trigger: 'change' },
        { validator: validator_Mobile, message: '请输入正确手机号', trigger: 'blur' },
    ],
})



let title = ref('新增会员')
let form = reactive({
    // re: {
    //     cardType: isUseBrandCard ? ["1", "2"] : ["2"],
    //     sex:'011002'
    // }
    re: {
        cardType: ["1", "2"] ,
        sex:'011002'
    }
})

watch(() => form.re.mobiles, (newvalue, oldvalue) => {
    console.log('监听 手机号 :>> ', newvalue);
    if (newvalue && newvalue.length == 11 && newvalue != oldvalue) {
        Api.Common.PcObjProcess.Do({ "functionName": "GetMemberInfo", "orgCode": "0004", "contentData": { "mobile": newvalue } })
            .then(res => {
                console.log('搜索会员res :>> ', res);
                if (res.result == '') {
                    title.value = '新增会员'
                    // form.re.cardType = isUseBrandCard ? ["1", "2"] : ["2"]
                    form.re.cardType =  ["1", "2"] 
                    form.re.birthday = ""
                    form.re.memberCode = ""
                    // cardType_disabled.value = isUseBrandCard ? "1" : "2"
                    cardType_disabled.value = ["1", "2"]
                    // form.re.name = ""
                    form.re.sex = "011002"
                } else {
                    console.log(res.memberLabel);
                    if(res.memberLabel){
                        form.re.tag = res.memberLabel
                        console.log(form.re.tag);
                        selectLabes.value = res.memberLabel.split(',').map(pair => {
                            const [tagName, color] = pair.split(':');
                            return { tagName, color };
                        });
                        
                    }
                    selectLabes.value = selectLabes.value.slice(0, 3) // 只显示3个标签
                    setForm(res)
                }
            })
    }
})
let cardType_disabled = ref(isUseBrandCard ? "1" : "2",)
// let isActive = ref(1)
// form.re.cardType = isActive.value
// const handleType = (cardType) => {
//     isActive.value = cardType
//     form.re.cardType = isActive.value
// }
// 编辑
const setForm = (user) => {
    console.log('user :>> ', user);
    title.value = '编辑会员'
    form.re = {
        "memberCode": user.memberCode,
        "mobiles": user.mobile,
        "name": user.name,
        "sex": user.sex,
        "birthday": user.birthday,
        "cardType": user.cardType,
        "tag":user.memberLabel
    }
    if (form.re.sex == '男') {
        form.re.sex = '011001'
    } else if (form.re.sex == '女') {
        form.re.sex = '011002'
    }
    cardType_disabled.value = form.re.cardType.join(',')
    console.log('cardType_disabled :>> ', cardType_disabled);
}
// 暴露方法
defineExpose({ setForm })
// 表单rules
// 取消
const emit = defineEmits(['emitCancel', 'emitSubmit'])
const handleCancel = (params) => {
    emit('emitCancel', 'cancel')
}
// 确认
const formRef = ref()
const loading_dialog = ref(false)
const handleSubmit = (params) => {
     console.log(form.re)
     if(!form.re.name) {
        ElNotification({
            title: '提示',
            message: '昵称不能为空',
            type: 'warning',
         })
	    return
	  }
	  
	  if(form.re.name.length > 15){
          ElNotification({
            title: '提示',
            message: '昵称过长，请不要超过15个字符',
            type: 'warning',
           })
		  return
	  }
      loading_dialog.value = true
    formRef.value.validate(valid => { //表单验证
        if (valid) {
            if (form.re.memberCode) {
                let data = {
                    "code": form.re.memberCode,
                    "mobile": form.re.mobiles,
                    "name": form.re.name,
                    "sex": form.re.sex,
                    "birthday": form.re.birthday,
                    "cardType": form.re.cardType.join(','),
                    'tag':form.re.tag || null,
                }
                // console.log('data :>> ', data);
                // return
                Api.Common.PcObjProcess.Do({ "functionName": "UpdateMember", "orgCode": "0004", "contentData": data }).then(res => {
                    console.log('编辑res :>> ', res);
                    ElNotification({
                        title: '提示',
                        message: '编辑成功',
                        type: 'success',
                    })
                    loading_dialog.value = true
                    emit('emitSubmit', { mobile: form.re.mobiles })
                }).catch(() => {
                    loading_dialog.value = false
                 })
            } else {
                let data = {
                    "orgCode": null,
                    "orgName": null,
                    "mobiles": form.re.mobiles,
                    "openId": null,
                    "wechat": null,
                    "name": form.re.name || null,
                    "sex": form.re.sex || null,
                    "birthday": form.re.birthday || null,
                    "cardType": form.re.cardType.join(','),
                    'tag':form.re.tag || '',
                }
                // console.log('data :>> ', data);
                // return
                Api.Common.PcObjProcess.Do({ "functionName": "MemberOpenCrad", "orgCode": "0004", "contentData": data }).then(res => {
                    console.log('新增res :>> ', res);
                    ElNotification({
                        title: '提示',
                        message: '注册成功',
                        type: 'success',
                    })
                    loading_dialog.value = true
                    emit('emitSubmit', { mobile: form.re.mobiles })
                }).catch(() => {
                    loading_dialog.value = false
                 })
            }
        }
    })

}

// 会员标签设置
const showLabel = ref(false)
const labelList = ref([])
const selectLabes = ref([])
const openChooseLab = ()=>{
    showLabel.value = true
    console.log(labelList.value);
    console.log(selectLabes.value);
    
    labelList.value.forEach(item => {
        const matchedLabel = selectLabes.value.find(selectItem => selectItem.tagName == item.tagName);
        if (matchedLabel) {
            item.active = true;  // 如果找到匹配的标签，设置 active 为 true
        }
    });
}
// 选中标签
const selectLabel = (index,k)=>{
  labelList.value[index].active = !labelList.value[index].active
 
}
const confirmLabel = ()=>{
    let arr = []
    // arr = labelList.value.flatMap(item => item.tagArry);
    arr = labelList.value
    if(arr.filter(item => item.active).length >3){
        ElNotification({
            title: '提示',
            message: '标签选择不可超过3个',
            type: 'warning',
        })
        return
    }
    selectLabes.value = arr.filter(item => item.active);
    showLabel.value = false
    function convertArrayToString(arr) {
    return arr
      .filter(item => item.active) // 只保留 active 为 true 的项
      .map(item => `${item.tagName}:${item.tagColor}`) // 转换为 "名称:颜色" 格式
      .join(','); // 用逗号连接字符串
  }
    const resultString = convertArrayToString(arr);
    form.re.tag  = resultString
     
    console.log(selectLabes.value);
}
// 获取标签列表
const gerLabel = ()=>{
    Api.Common.PcObjProcess.Do({ "functionName": "GetMemberTag",  "contentData": '' })
    .then(res=>{
        console.log(res);
        labelList.value = res.result.flatMap(item => item.tagArry)
    })
}
gerLabel()
</script>
  
<style  lang="scss" scoped>
.dialog-box {

    ::v-deep {
        .el-dialog {
            width: 700px;
            // height: 800px;
            border-radius: 16px;
            padding-left: 60px;
            padding-right: 60px;
            padding-bottom: 40px;
        }

        .el-dialog__title {
            font-weight: bold;
            font-size: 20px;
            color: #212121;
            line-height: 36px;
            // padding-left: 60px;
        }

        .el-divider {
            margin: 0;
        }

        .el-form-item__label {
            font-size: 16px;
            color: #212121;

        }
    }
    .label{
        padding: 10px 12px;
        display: flex;
        align-items: center;
        position: relative;
        // justify-content: space-between;
        .label-title{
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 16px;
            color: #212121;
            line-height: 16px;
        }
        .label-main{
            display: flex;
            align-items: center;
            .label-value{
                //width: 100px;
                padding: 0 15px; 
                height: 40px;
                border-radius: 8px;
                text-align: center;
                line-height: 40px;
                background: #ffee99;
                color: #212121;
                margin-left: 10px;
            }
        }
        
        .label-choose{
            position: absolute;
            padding: 0 12px;
            right: 0px;
            cursor: pointer;
            height: 40px;
            // background: #FFD400;
            border: 1px solid #FF6A00;
            border-radius: 8px;
            text-align: center;
            line-height: 40px;
            color: #FF6A00;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .addimg {
                margin-right: 8px;
                width: 24px;
                height: 24px;
            }
            .addbq {
                font-weight: 400;
                font-size: 16px;
                color: #FF6A00;
            }
        }
    }
    .footer-box {
        margin-top: 60px;
        display: flex;
        justify-content: center;

        .cancel {
            width: 160px;
            height: 60px;
            background: #FFFFFF;
            border-radius: 8px;
            border: 1px solid #FF6A00;
            font-size: 24px;
            color: #FF6A00;
        }

        .submit {
            width: 160px;
            height: 60px;
            background: #FF6A00;
            border-radius: 8px;
            font-size: 24px;
            color: #FFFFFF;
            margin-left: 30px;
        }
    }
}

.form {

    ::v-deep {
        .el-form-item__label {
            line-height: 48px;
        }

        .el-select__wrapper {
            height: 48px;
            // background: #F9F9F9;
            border-radius: 8px;
            font-weight: 400;
            font-size: 16px;
            color: #212121;
        }

        .el-input__wrapper {
            height: 48px;
            // background: #F9F9F9;
            border-radius: 8px;
            font-weight: 400;
            font-size: 16px;
            color: #212121;
        }
    }

    .button-box {
        display: flex;

        // justify-content: space-between;
        .button {
            width: 160px;
            height: 48px;
            background: #FFFFFF;
            border-radius: 8px;
            border: 1px solid #E6E6E6;
            font-weight: 400;
            font-size: 18px;
            color: #666666;
            // border: 0;
        }

        .active {
            background: #FFD400;
            font-size: 18px;
            color: #212121;
        }

        ::v-deep {
            .el-checkbox-button {
                border: 0;
                margin-right: 10px;
            }

            .el-checkbox-button__inner {
                border-radius: 8px;
                border: 1px solid #E6E6E6;
                color: #212121;
            }

            .is-checked {
                .el-checkbox-button__original {
                    display: none;
                }

                .el-checkbox-button__inner {
                    background: #FFD400;
                    border-radius: 8px;
                    border: 1px solid #FFD400;
                    color: #212121;
                }
            }
        }
    }
}
.popup{
    .popup-title{
        font-family: Microsoft YaHei;
        font-weight: bold;
        font-size: 24px;
        color: #212121;
        line-height: 24px;
        text-align: center;
    }
    .popup-value{
        font-family: Microsoft YaHei;
        font-weight: bold;
        font-size: 18px;
        color: #212121;
        line-height: 18px;
        padding: 20px 0 0;
        .popup-value-tip{
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 16px;
            color: #212121;
            line-height: 16px;
        }
    }
    .popup-main{
        padding: 0 10px;
       
        .popup-main-title{
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 16px;
            color: #212121;
            line-height: 16px;
        }
        .popup-main-value{
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            .popup-main-item{
                cursor: pointer;
                // width: 100px;
                padding: 0 20px;
                height: 48px;
                background: #E6E6E6;
                border-radius: 8px;
                font-family: Microsoft YaHei;
                font-weight: 400;
                font-size: 16px;
                color: #212121;
                line-height: 48px;
                text-align: center;
                margin-left: 20px;
                margin-top: 20px;
                &.active{
                    background: #FFEE99 !important;
                    
                }
            }
        }
       
    }
    .popup-btn{
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        padding: 60px 50px 20px;
        .popup-btn-cancle{
            cursor: pointer;
            width: 160px;
            height: 60px;
            background: #FFFFFF;
            border-radius: 8px;
            border: 1px solid #FF6A00;
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 24px;
            color: #FF6A00;
            line-height: 60px;
            text-align: center;
            
        }
        .popup-btn-confirm{
            cursor: pointer;
            width: 160px;
            height: 60px;
            background: #FF6A00;
            border-radius: 8px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            font-size: 24px;
            color: #FFFFFF;
            line-height: 60px;
            text-align: center;
        }

    
    }

}

::v-deep(.el-radio__inner) {
        // margin-left: 20px;
        width: 20px;
        height: 20px
      }

      ::v-deep(.el-radio__input.is-checked+.el-radio__label) {
        color: #212121;
      }

      ::v-deep(.el-radio__input.is-checked .el-radio__inner) {
        border-color: #ff6a00;
        /* 选中状态边框颜色 */
        background-color: #ffffff;
        /* 选中状态背景颜色 */
      }

      ::v-deep(.el-radio__inner:after) {
        background-color: #ff6a00;
        width: 8px;
        height: 8px;
      }
</style>
  